package hasthi.tools.analyze;

import hasthi.common.BaseContext;
import hasthi.common.HasthiException;
import hasthi.common.ManagementNotifier;
import hasthi.common.XmlBeanUtils;
import hasthi.common.HasthiException.FaultCode;
import hasthi.common.constants.WsrfConstants;
import hasthi.container.notifier.WSMessengerNotifier;
import hasthi.manager.monitering.EventListener;
import hasthi.manager.monitering.MoniteringAgent;
import hasthi.test.ClientSetDocument;
import hasthi.tools.analyze.suite.EchoClientSet;
import hasthi.wsrf.WsrfClientUtils;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.xmlbeans.XmlObject;
import org.xmlpull.v1.builder.XmlBuilderException;
import org.xmlpull.v1.builder.XmlElement;

import wsrf.GetResourcePropertyDocumentResponseDocument;
import xsul.invoker.DynamicInfosetInvokerException;
import xsul.ws_addressing.WsaEndpointReference;
import xsul.ws_addressing.WsaInvoker;
import xsul.xbeans_util.XBeansUtil;

public class PerfAgent implements EventListener{
    private  BaseContext baseConfigContext;
    private ManagementNotifier notifier;
    
    ExecutorService executorService;
    protected MoniteringAgent moniteringAgent;

    private static PerfAgent agent;
    protected PerfAgent() throws HasthiException{
        baseConfigContext = new BaseContext(null);
        //subscribe to Notification channel 
        
        for(int i = 0;i<3;i++){
            try {
                moniteringAgent = new MoniteringAgent(baseConfigContext.getMessageBrokerUrl(),"PERF");
                break;
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        
        moniteringAgent.addTrigger(this);
        moniteringAgent.startMonitering();
        notifier = new WSMessengerNotifier(baseConfigContext.getMessageBrokerUrl(),"PERF","resultSender");
        executorService = Executors.newCachedThreadPool();
        agent = this;
    }

    public String getSearchPath() {
        // TODO Auto-generated method stub
        return null;
    }

    public void performTriggerAction(XmlObject event, XmlObject[] matchingResults)
            throws HasthiException {
        System.out.println(event + " received 1");
        if(event instanceof ClientSetDocument){
            System.out.println("test thread scheduling");
            EchoClientSet clientSet = new EchoClientSet();
            clientSet.init(event);
            executorService.execute(clientSet);
//        }else if(event instanceof ServiceSetDocument){
//            
//        }else if(event instanceof ManagerSetDocument){
//            
        }else{
            System.out.println("Event ignored" + event.getClass());
        }
        
    }
    
    public void sendEvent(XmlObject event) throws HasthiException{
        notifier.sendEvent(event);
    }

    public static PerfAgent getInstance() throws HasthiException{
        if(agent == null){
            agent = new PerfAgent();
        }
        return agent;
    }
    
    
    protected boolean verifyService(String serviceUrl) throws HasthiException{
        try {
            WsaInvoker wsaInvoker = new WsaInvoker();
            wsaInvoker.setDefaultAction(new URI(WsrfConstants.WSA_ACTION_GET_RESOURCE_PROPERTY_DOCUMENT));
            wsaInvoker.setTargetEPR(new WsaEndpointReference(new URI(serviceUrl)));
            
            XmlElement responseXmlEle = wsaInvoker.invokeMessage(XBeansUtil.xmlObjectToXmlElement(WsrfClientUtils.buildGetResourcePropertyDocumentRequest()));
            XmlObject response = XBeansUtil.xmlElementToXmlObject(responseXmlEle);
            if(response instanceof GetResourcePropertyDocumentResponseDocument){
                return true;
            }else{
                System.out.println(XmlBeanUtils.prettyPrint(response));
                return false;   
            }
        } catch (DynamicInfosetInvokerException e) {
            throw new HasthiException(e,FaultCode.InternalServiceError);
        } catch (XmlBuilderException e) {
            throw new HasthiException(e,FaultCode.ErrorAtClientWhileWsCall);
        } catch (URISyntaxException e) {
            throw new HasthiException(e,FaultCode.ErrorAtClientBeforeWsCall);
        }
     }
    
    public static void main(String[] args) throws HasthiException {
        new PerfAgent();
    }
}
